import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter_deer/card_reader.dart';
import 'package:flutter_deer/net/conmmon_net_util.dart';
import 'package:flutter_deer/net/dio_utils.dart';
import 'package:flutter_deer/net/http_api.dart';
import 'package:flutter_deer/res/colors.dart';
import 'package:flutter_deer/res/constant.dart';
import 'package:flutter_deer/util/aes_cbc_util.dart';
import 'package:flutter_deer/util/device_info_plus.dart';
import 'package:flutter_deer/util/print/print_engine_gb.dart';
import 'package:flutter_deer/util/speak/tts_engine_default.dart';
import 'package:flutter_deer/util/speak/tts_engine_gb.dart';
import 'package:flutter_deer/widgets/press_blue_button.dart';
import 'package:get/get.dart';

class SettingPage5Device extends StatefulWidget {
  const SettingPage5Device({super.key});

  @override
  State<SettingPage5Device> createState() => _SettingPage5DeviceState();
}

class _SettingPage5DeviceState extends State<SettingPage5Device> {
  final RxString scanResult = ''.obs;
  final RxString printResult = ''.obs;
  final RxString windowsInfo = ''.obs;
  final RxBool switchSpeakJb = true.obs; // 佳博播报
  final RxBool switchSpeakWindows = true.obs; // windows播报
  final RxBool switchPrintJb = true.obs; // 佳博打印
  // final RxBool switchPrintWindows = true.obs; // windows打印

  @override
  void initState() {
    super.initState();
    _refreshPrinter();
    _getWindowsInfo();
    // 初始化开关状态
    switchSpeakJb.value = SpUtil.getBool(Constant.switchSpeakJb, defValue: false) == true;
    switchSpeakWindows.value = SpUtil.getBool(Constant.switchSpeakWindows, defValue: true) == true;
    switchPrintJb.value = SpUtil.getBool(Constant.switchPrintJb, defValue: false) == true;
    // switchPrintWindows.value = SpUtil.getBool(Constant.switchPrintWindows, defaultValue: true);
  }

  @override
  Widget build(BuildContext context) {
    final mController = TextEditingController();
    return Scaffold(
      body: Column(
        children: [
          // 扫码枪
          _buildMdcItem([
            Icon(Icons.qr_code_scanner, color: Colors.blue.shade700, size: 30),
            SizedBox(width: 10),
            Text('扫码枪', style: TextStyle(color: Colours.text, fontSize: 16, fontWeight: FontWeight.bold)),
          ], [
            Expanded(
              child: TextFormField(
                controller: mController,
                decoration: const InputDecoration(
                  labelText: '点击此处，聚焦到输入框后请扫码',
                ),
                validator: (value) {
                  if (value?.isEmpty ?? true) {
                    return '请输入枪号';
                  }
                  return null;
                },
              ),
            ),
          ], [
            // PressBlueButton(text: '常用商品', onPressed: () => null),
          ]),

          // 读卡器
          _buildMdcItem([
            Icon(Icons.credit_card, color: Colors.blue.shade700, size: 30),
            SizedBox(width: 10),
            Text('读卡器', style: TextStyle(color: Colours.text, fontSize: 16, fontWeight: FontWeight.bold)),
          ], [
            Obx(() => Expanded(
                  child: Text(
                    '读卡结果：$scanResult',
                  ),
                )),
          ], [
            PressBlueButton(text: '点击蜂鸣', onPressed: () => _beep()),
            const SizedBox(height: 15),
            PressBlueButton(text: '点击读卡', onPressed: () => _readCard()),
          ]),

          // 佳博打印
          _buildMdcItem([
            Icon(Icons.local_print_shop, color: Colors.blue.shade700, size: 30),
            // Icon(Icons.campaign, color: Colors.blue.shade700, size: 30),
            // Icon(Icons.mic_external_on, color: Colors.blue.shade700, size: 30),
            Icon(Icons.speaker, color: Colors.blue.shade700, size: 30),
            SizedBox(width: 5),
            Text('佳博', style: TextStyle(color: Colours.text, fontSize: 16, fontWeight: FontWeight.bold)),
          ], [
            Obx(() => Expanded(
                  child: Text(
                    '$printResult',
                  ),
                )),
          ], [
            Row(
              children: [
                PressBlueButton(text: '点击试听', onPressed: () => _beepJb()),
                const SizedBox(width: 10),
                PressBlueButton(text: '点击打印', onPressed: () => _printJb()),
              ],
            ),
            // PressBlueButton(text: '点击试听', onPressed: () => _beep()),
            // const SizedBox(height: 10),
            // PressBlueButton(text: '点击打印', onPressed: () => _print()),
            const SizedBox(height: 10),
            Obx(() => Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Text(switchSpeakJb.value ? '播报已启用' : '播报已禁用', style: const TextStyle(color: Colours.green, fontSize: 14, fontWeight: FontWeight.bold)),
                    const SizedBox(width: 1),
                    Switch(
                      value: switchSpeakJb.value,
                      onChanged: (value) {
                        switchSpeakJb.value = value;
                        SpUtil.putBool(Constant.switchSpeakJb, value);
                      },
                      activeColor: Theme.of(context).primaryColor,
                      activeTrackColor: Theme.of(context).primaryColor.withOpacity(0.5),
                      inactiveThumbColor: Colors.grey[400],
                      inactiveTrackColor: Colors.grey[300],
                    ),
                  ],
                )),
            const SizedBox(height: 0),
            Obx(() => Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Text(switchPrintJb.value ? '打印已启用' : '打印已禁用', style: const TextStyle(color: Colours.green, fontSize: 14, fontWeight: FontWeight.bold)),
                    const SizedBox(width: 1),
                    Switch(
                      value: switchPrintJb.value,
                      onChanged: (value) {
                        switchPrintJb.value = value;
                        SpUtil.putBool(Constant.switchPrintJb, value);
                      },
                      activeColor: Theme.of(context).primaryColor,
                      activeTrackColor: Theme.of(context).primaryColor.withOpacity(0.5),
                      inactiveThumbColor: Colors.grey[400],
                      inactiveTrackColor: Colors.grey[300],
                    ),
                  ],
                )),
          ]),

          // 本机播报
          _buildMdcItem([
            Icon(Icons.desktop_windows_outlined, color: Colors.blue.shade700, size: 30),
            SizedBox(width: 5),
            Text('本机', style: TextStyle(color: Colours.text, fontSize: 16, fontWeight: FontWeight.bold)),
          ], [
            Obx(() => Expanded(
                  child: Text(
                    '$windowsInfo',
                  ),
                )),
          ], [
            Row(
              children: [
                Obx(() => Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        Text(switchSpeakWindows.value ? '播报已启用' : '播报已禁用', style: const TextStyle(color: Colours.green, fontSize: 14, fontWeight: FontWeight.bold)),
                        const SizedBox(width: 1),
                        Switch(
                          value: switchSpeakWindows.value,
                          onChanged: (value) {
                            switchSpeakWindows.value = value;
                            SpUtil.putBool(Constant.switchSpeakWindows, value);
                          },
                          activeColor: Theme.of(context).primaryColor,
                          activeTrackColor: Theme.of(context).primaryColor.withOpacity(0.5),
                          inactiveThumbColor: Colors.grey[400],
                          inactiveTrackColor: Colors.grey[300],
                        ),
                      ],
                    )),
                PressBlueButton(text: '点击试听', onPressed: () => _beepWindows()),
              ],
            ),
          ]),
        ],
      ),
    );
  }

  /// 构建MDC项
  Widget _buildMdcItem(
    List<Widget> titleTop,
    List<Widget> titleBottom,
    List<Widget> titleRight,
  ) {
    final card = Card(
      margin: const EdgeInsets.symmetric(horizontal: 5, vertical: 5),
      shape: RoundedRectangleBorder(
        side: BorderSide(color: Colors.blue.shade700, width: 1),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Container(
        width: 360,
        height: 145,
        padding: const EdgeInsets.all(16),
        child: Stack(
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: titleTop,
                ),
                const Spacer(),
                Row(
                  children: titleBottom,
                ),
                const SizedBox(height: 5),
              ],
            ),

            // 设置图标
            Positioned(
              top: 0,
              right: 0,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.end,
                crossAxisAlignment: CrossAxisAlignment.end,
                children: titleRight,
              ),
            ),

            // // 设置图标
            // Positioned(bottom: 6, right: 2, child: Icon(Icons.print_sharp, color: Colors.blue.shade700, size: 30)),
          ],
        ),
      ),
    );
    return card;
  }

  // 蜂鸣
  void _beep() {
    CardReader.setupLogListener();
    CardReader.beep().then((value) {
      print('蜂鸣结果: $value');
    }).catchError((error) {
      print('蜂鸣失败: $error');
    });
  }

  // 读卡
  void _readCard() {
    scanResult.value = '读卡中...';
    CardReader.readUid().then((value) {
      scanResult.value = '$value ${AESCBCUtil.decrypt(value['data'])}';
    }).catchError((error) {
      scanResult.value = '读卡失败: $error';
    });
  }

  // 刷新打印机
  void _refreshPrinter() {
    printResult.value = '刷新中...';
    CommonNetUtil.requestNetwork<Map<String, dynamic>>(Method.post, url: HttpApi.getPrinterList, params: {
      'pageNo': 1,
      'pageSize': 10,
      'deviceType': 'ydy',
    }, onSuccess: (data) {
      // 解析并保存打印机数据
      if (data != null) {
        try {
          print('接收到的原始数据类型: ${data.runtimeType}');
          // 解析并保存打印机数据
          if (data['list'] is List && (data['list'] as List).isNotEmpty) {
            final list = data['list'] as List;
            final des = StringBuffer();
            final element = list.first;
            des.write('''品牌: ${element['deviceBrandName']} [${data['total']}]
编号: ${element['deviceCode']}
状态: ${element['statusName']}''');
            printResult.value = des.toString();
          } else {
            printResult.value = '设备暂无';
          }
        } catch (e, stackTrace) {
          printResult.value = '处理失败: ${e.toString()}';
        }
      }
    }, onError: (code, msg) {
      printResult.value = '刷新失败: $msg';
    });
  }

  // 获取窗口信息
  void _getWindowsInfo() {
    DeviceUniqueIdUtil.getUniqueId().then((value) {
      print('value: ${value?.toMap()}');
      windowsInfo.value = '''系统: ${value?.productName} (${value?.editionId} ${value?.displayVersion})
时间: ${value?.installDate}
名称: ${value?.computerName} (${value?.userName})''';
    });
  }

  // Windows点击试听
  Future<void> _beepWindows() async {
    final ttsEngineDefault = TtsEngineDefault();
    // await ttsEngineDefault.init();
    await ttsEngineDefault.speak(' 语音播报，这是一条测试消息');
  }

  // 佳博点击
  Future<void> _beepJb() async {
    final ttsEngineGbSpeaker = TtsEngineGbSpeaker();
    await ttsEngineGbSpeaker.speak(' 佳博语音播报，这是一条测试消息');
  }

  // 佳博打印
  Future<void> _printJb() async {
    final printEngineGb = PrintEngineGb();
    await printEngineGb.testPrint();
  }
}
